from django.shortcuts import render
from content.user_agents import agents
from data.models import MyData
from requests_html import HTMLSession
from datetime import datetime
from django.core.paginator import Paginator

import random
import psycopg2
import pandas as pd
import requests
import time
import os

from m_baoke import settings
from dtk_open_platform import DtkOpenPlatform

import top.api


def index_view(request):
    dt = datetime.now()
    objects = MyData.objects.filter(discount_start__lte=dt, discount_end__gt=dt).order_by('id')
    paginator = Paginator(objects, 20)

    page = request.GET.get('page', 1)
    goods = paginator.get_page(page)
    return render(request, 'content/index.html', {'goods': goods})


def detail_view(request, product_id):
    product_id = '603627832635'
    goods = MyData.objects.get(goods_id=product_id)
    content = {'goods_image': goods.goods_image, 'goods_name': goods.goods_name, 'goods_sales': goods.goods_sales,
               'goods_price': goods.goods_price, 'coupon_value': goods.coupon_value,
               'goods_coupon_spread_url': goods.goods_coupon_spread_url, 'goods_detail_url': goods.goods_detail_url}
    # 商品详情
    # get_detail(goods.goods_detail_url)

    return render(request, 'content/detail.html', content)


def get_detail(url):
    desc = None
    idx = random.randint(0, len(agents) - 1)
    headers = {'user-agent': agents[idx]}

    session = HTMLSession()
    tb = session.get(url)
    links = tb.links
    print(links)
    # pattern = re.compile(r'{"descUrl":(.*?)"}')
    # match = pattern.search(r.text)
    # if match is not None:
    #     group_0 = match.group()
    #     obj = json.loads(group_0)
    #     url_2 = 'http:' + obj['descUrl']
    #     r_2 = requests.get(url_2, headers=headers)
    #     desc = r_2.text

    return desc


# 取TOP10 销量、佣金
def get_top10(request):
    dt = datetime.now()
    goods = MyData.objects.filter(discount_start__lte=dt, discount_end__gt=dt).order_by('-commission')[
            :1]
    # 生成分享
    goods_list = [
        {'goods_id': good.goods_id, 'title': good.goods_name, 'picture': good.goods_image, 'price': good.goods_price,
         'coupon_value': good.coupon_value, 'coupon_url': good.coupon_url, 'tbk_url': good.tbk_url} for good in goods]
    template_msg = """
{title}
【在售价】{price}元
【优惠券】{coupon_value}
-----------------
【立即领券】点击链接即可领券购买：{coupon_url}
"""
    url = 'http://127.0.0.1:5700/send_group_msg'
    # 发送图像：[CQ:image,file=%子文件夹\文件名%]
    for g in goods_list:
        # 保存产品图
        image = requests.get(g['picture'])
        image_dir = os.path.join(settings.MEDIA_ROOT, 'tmp.jpg')
        with open(image_dir, 'wb') as f:
            f.write(image.content)

        # 图片
        payload = {'user_id': '330161849', 'group_id': '134914479', 'message': '[CQ:image,file=%s]' % image_dir}
        try:
            requests.get(url, params=payload)
            time.sleep(1)
        except requests.exceptions.ConnectionError:
            pass

        # 计算短链
        short_url = get_short_url(g['goods_id'])
        if short_url is not None:
            msg = template_msg.format(title=g['title'], price=g['price'], coupon_value=g['coupon_value'],
                                      coupon_url=short_url)
            payload = {'user_id': '330161849', 'group_id': '134914479', 'message': msg}
            try:
                requests.get(url, params=payload)
                time.sleep(1)
            except requests.exceptions.ConnectionError:
                pass
    # sample: http://192.168.1.123:5700/send_private_msg?user_id=123456&message=你好
    return render(request, 'content/top10.html', {'goods': goods})


def pd_read_sql():
    # postgres config
    postgres_host = "127.0.0.1"  # 数据库地址
    postgres_port = "5432"  # 数据库端口
    postgres_user = "postgres"  # 数据库用户名
    postgres_password = ""  # 数据库密码
    postgres_database = ""  # 数据库名字
    postgres_table1 = ""  # 数据库中的表的名字

    # connection string
    conn_string = "host=" + postgres_host + " port=" + postgres_port + " dbname=" + postgres_database + \
                  " user=" + postgres_user + " password=" + postgres_password
    conn = psycopg2.connect(conn_string)

    sql_command1 = "select * from".format(postgres_table1)

    try:
        data1 = pd.read_sql(sql_command1, conn)
        if data1.shape[0] == 0:
            print("there is no data in !")
    except Exception as e:
        print("load data from postgres failure !")
        exit()


# 大淘客： 计算短链接
def get_short_url(goods_id):
    response = {
        'msg': '服务器错误',
        'code': -1,
        'time': 1554365022200
    }
    app_key = '5e03270657104'
    app_secret = 'd66e879f354a20aa3d2b71ccc5e7487a'
    version = 'v1.1.1'  # 当前版本号
    url = 'https://openapi.dataoke.com/api/tb-service/get-privilege-link'
    method = 'get'
    send = DtkOpenPlatform()
    data = {'appKey': app_key,
            'version': version,
            'goodsId': goods_id
            }
    response = send.open_platform_send(method=method, url=url, args=data, key=app_secret)
    if response['code'] == 0:
        return response['data']['shortUrl']
    else:
        return None


def get_tbk_short_url(url_list):
    pass
